
var Class = require('ClassBuilder');

var MessageBuffer = Class(function( _public ) {

    _public._construct = function() {
        this.buffers        = [];
        this.totalLength    = 0;
    };

    _public.pushChunk = function( buffer ) {

        this.buffers.push(buffer);

        this.totalLength += buffer.length;

    };

    _public.concat = function() {

        if( this.buffers.length<1 )
            return false;

        var concatedBuffer = new Buffer( this.totalLength );

        var posi = 0;
        this.buffers.forEach(function( chunk, index ) {
            chunk.copy( concatedBuffer, posi );
            posi += chunk.length;
        });

        delete this.buffers;

        this.buffers = [];

        return this.buffers[0] = concatedBuffer;

    };

    _public.toString = function() {

        return this.concat().toString();

    };

    _public.selfSizeCheck = function() {

        // Todo: 进行缓冲区的长度检查，若长度已到达，则取出已完整到达的消息体部分，存进一个新的Buffer返回，并清楚原buffer里已经取出的那部分
        var buffers = this.buffers;

        if( buffers.length<1 )
            return false;

        var firstBuffer = buffers[0];

        var sizeByteCount = firstBuffer[0];

        var sizeByteBuffer = new Buffer( 4 );
        sizeByteBuffer.fill(0);

        firstBuffer.copy( sizeByteBuffer, 4-sizeByteCount, 1, 1+sizeByteCount );

        totalSize = sizeByteBuffer.readUInt32BE(0);

        if( this.totalLength >= totalSize && totalSize>0 )
            return this.takeAwayPartBuffer( 0, totalSize ).slice( 1+sizeByteCount );

        else
            return false;

    };

    _public.takeAwayPartBuffer = function( start, end ) {

        if( start == end )
            return new Buffer(0);

        var concatedBuffer = this.concat();

        var partTakeAway = concatedBuffer.slice( start, end );

        // end值为负数，表明为从后往前数，计算其对应的正数值
        if( end<0 )
            end = concatedBuffer.length+end+1;

        // 重置缓冲区数组
        delete this.buffers;
        this.buffers = [];

        // 将 没有被取出 的部分合并
        if( start>0 )
            this.buffers.push( concatedBuffer.slice( 0, start ) );
        if( end<concatedBuffer.length )
            this.buffers.push( concatedBuffer.slice( end ) );

        // 修正总长度计数，因为被取走了一部分
        this.totalLength -= partTakeAway.length;

        this.concat();

        return partTakeAway;

    };

});

module.exports = MessageBuffer;